/*
知识点：不同集合之间的文档引用(DBRef)，配合populate()来实现
描述: 
	以下代码展示了，news集合文档里面引用了，users集合里面的文档
	输出的数如下：author字段的内容全部来自，users的文档
	{ 
		_id: 5a6d7bd221af6f0fd9dcc1e6,
    	title: 'this is a new title!',
    	author: { _id: 5a6d7bd221af6f0fd9dcc1e5, name: 'htl', __v: 0 },
    	__v: 0 
    } 

*/
const mongoose = require('mongoose');
const uri = 'mongodb://localhost/htl';
const db = mongoose.connect(uri);

const User = mongoose.model('users',{
	name: String
})
const News = mongoose.model('news',{
	title: String,
	author: {
		type: mongoose.Schema.ObjectId,
		ref: 'users'   //表示引用哪个个集合，这里用users集合
	}
})

const user = new User({
	name: 'htl'
})
const news = new News({
	title: 'this is a new title!',
	author: user
})

user.save((err) => {
	if(err) return console.log('user save is fail:'+err);
	news.save((err) => {
		if(err) return console.log('news save is fail:'+err);
		//这里用populate()方法来填充author字段
		News.find().populate('author').exec((err,doc) => {
			if(err) return console.log('news find is fail:'+err);
			console.log(doc)
		})
	})
})